const app = getApp()
const api = require('../../utils/api')

Page({
  data: {
    type: 'glucose',       // 记录类型：glucose, bloodPressure, weight
    title: '',
    value: '',
    systolic: '',          // 收缩压
    diastolic: '',         // 舒张压
    glucose: '',           // 血糖值
    weight: '',            // 体重值
    date: '',
    time: '',
    note: '',              // 备注
    submitDisabled: true,
    isEditMode: false,     // 是否是编辑模式
    timestamp: '',         // 编辑模式下记录的时间戳
    isCombinedMode: false, // 是否是综合添加模式
    recordDate: '',        // 记录日期
    recordTime: '',        // 记录时间
    isFormValid: false,     // 表单是否有效
    submitting: false,      // 是否正在提交
    recordId: ''           // 记录ID
  },

  /**
   * 页面加载时的生命周期函数
   */
  onLoad(options) {
    console.log('记录页面加载, 参数:', options);
    const { type, id, timestamp, isEditMode: editModeParam } = options;
    
    // 设置当前日期和时间
    const now = new Date();
    const date = now.toISOString().slice(0, 10);
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const time = `${hour}:${minute}`;
    
    let title = '记录';
    let isCombinedMode = false;
    let isEditMode = editModeParam === 'true' || false;
    
    switch (type) {
      case 'bloodPressure':
        title = '血压记录';
        break;
      case 'glucose':
        title = '血糖记录';
        break;
      case 'weight':
        title = '体重记录';
        break;
      case 'combined':
        title = '健康记录';
        isCombinedMode = true;
        break;
      default:
        console.warn('未识别的记录类型:', type);
        break;
    }
    
    if (id && timestamp) {
      title = '编辑记录';
      isEditMode = true;
      console.log('编辑模式, 将加载记录:', { id, type, timestamp });

      // 获取事件通道，监听传递的记录数据
      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel) {
        eventChannel.on('editRecord', (data) => {
          console.log('接收到编辑记录数据:', data);
          if (data && data.record) {
            this.fillFormWithRecordData(data.record, type);
          } else {
            // 如果没有通过事件通道接收到数据，使用id加载
            this.loadRecord(id, type);
          }
        });
      } else {
        // 如果没有事件通道，使用id加载
        this.loadRecord(id, type);
      }
    }
    
    // 设置页面标题
    wx.setNavigationBarTitle({
      title
    });
    
    console.log('初始化页面数据:', {
      type, isEditMode, isCombinedMode, date, time
    });
    
    this.setData({
      type: type || 'glucose',
      isEditMode,
      isCombinedMode,
      timestamp: timestamp || '',
      recordDate: date,
      recordTime: time,
      title,
      recordId: id || ''
    });
    
    // 初始化表单验证
    this.checkForm();
  },
  
  /**
   * 直接使用记录数据填充表单
   */
  fillFormWithRecordData(record, type) {
    console.log('使用记录数据填充表单:', record);
    
    if (!record) return;
    
    try {
      const recordDate = new Date(record.timestamp);
      const date = recordDate.toISOString().split('T')[0];
      const hour = String(recordDate.getHours()).padStart(2, '0');
      const minute = String(recordDate.getMinutes().toString().padStart(2, '0'));
      const time = `${hour}:${minute}`;
      
      // 设置记录数据
      const data = {
        recordDate: date,
        recordTime: time,
        note: record.note || ''
      };
      
      switch (type) {
        case 'glucose':
          data.glucose = String(record.value || '');
          break;
        case 'bloodPressure':
          data.systolic = String(record.systolic || '');
          data.diastolic = String(record.diastolic || '');
          break;
        case 'weight':
          data.weight = String(record.value || '');
          break;
      }
      
      console.log('设置表单数据:', data);
      this.setData(data);
      
      // 确保表单验证正确运行
      setTimeout(() => {
        this.checkForm();
      }, 100);
    } catch (error) {
      console.error('填充表单数据失败:', error);
      wx.showToast({
        title: '加载记录失败',
        icon: 'none'
      });
    }
  },

  onInput(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [field]: value
    }, () => {
      this.checkForm()
    })
  },

  checkForm() {
    const { 
      type, isEditMode, isCombinedMode, 
      glucose, systolic, diastolic, weight, 
      recordDate, recordTime 
    } = this.data;
    
    console.log('执行表单验证, 当前数据:', { 
      type, isCombinedMode, 
      glucose, systolic, diastolic, weight,
      recordDate, recordTime
    });
    
    let isValid = false;
    
    // 检查日期和时间是否已设置
    if (!recordDate || !recordTime) {
      console.log('日期或时间未设置');
      this.setData({ isFormValid: false });
      return false;
    }
    
    if (isCombinedMode) {
      // 综合模式 - 至少一个指标必须有效
      const hasValidGlucose = glucose && !isNaN(parseFloat(glucose)) && parseFloat(glucose) > 0;
      const hasValidBP = systolic && diastolic && 
                       !isNaN(parseFloat(systolic)) && !isNaN(parseFloat(diastolic)) &&
                       parseFloat(systolic) > 0 && parseFloat(diastolic) > 0;
      const hasValidWeight = weight && !isNaN(parseFloat(weight)) && parseFloat(weight) > 0;
      
      isValid = hasValidGlucose || hasValidBP || hasValidWeight;
      
      console.log('综合模式验证:', {
        hasValidGlucose, hasValidBP, hasValidWeight, isValid
      });
    } else {
      // 单项模式
      switch (type) {
        case 'glucose':
          isValid = glucose && !isNaN(parseFloat(glucose)) && parseFloat(glucose) > 0;
          console.log('血糖验证:', { glucose, isValid });
          break;
        case 'bloodPressure':
          isValid = systolic && diastolic && 
                  !isNaN(parseFloat(systolic)) && !isNaN(parseFloat(diastolic)) &&
                  parseFloat(systolic) > 0 && parseFloat(diastolic) > 0;
          console.log('血压验证:', { systolic, diastolic, isValid });
          break;
        case 'weight':
          isValid = weight && !isNaN(parseFloat(weight)) && parseFloat(weight) > 0;
          console.log('体重验证:', { weight, isValid });
          break;
        default:
          isValid = false;
          console.log('未知类型验证失败:', type);
      }
    }
    
    console.log('最终表单验证结果:', isValid);
    
    // 更新表单有效性状态
    this.setData({
      isFormValid: isValid
    });
    
    return isValid;
  },

  /**
   * 提交记录
   */
  async submitRecord() {
    try {
      this.setData({ submitting: true });
      let success = false;
      
      // 获取格式化后的记录数据
      const recordData = this.formatRecordData();
      
      // 当前是编辑模式
      if (this.data.isEditMode) {
        console.log('编辑模式提交记录:', {
          type: this.data.type,
          recordId: this.data.recordId || this.data.timestamp,
          data: recordData
        });
        
        // 编辑现有记录
        success = await api.health.updateRecord(
          this.data.type,
          this.data.recordId || this.data.timestamp,
          recordData
        );
      } else {
        // 不同模式下的处理逻辑
        if (this.data.isCombinedMode) {
          // 综合模式：添加所有填写了的数据
          const dataUpdated = {}; // 跟踪已更新的数据类型

          // 处理血糖数据
          if (this.data.glucose !== '' && !isNaN(parseFloat(this.data.glucose))) {
            const timestamp = this.formatTimestamp();
            await api.health.addRecord('glucose', {
              value: parseFloat(this.data.glucose),
              timestamp,
              period: this.data.period,
              note: this.data.note
            });
            dataUpdated.glucose = true;
          }

          // 处理血压数据
          if (this.data.systolic !== '' && this.data.diastolic !== '' &&
              !isNaN(parseFloat(this.data.systolic)) && !isNaN(parseFloat(this.data.diastolic))) {
            const timestamp = this.formatTimestamp();
            await api.health.addRecord('bloodPressure', {
              systolic: parseInt(this.data.systolic),
              diastolic: parseInt(this.data.diastolic),
              timestamp,
              period: this.data.period,
              note: this.data.note
            });
            dataUpdated.bloodPressure = true;
          }

          // 处理体重数据
          if (this.data.weight !== '' && !isNaN(parseFloat(this.data.weight))) {
            const timestamp = this.formatTimestamp();
            await api.health.addRecord('weight', {
              value: parseFloat(this.data.weight),
              timestamp,
              period: this.data.period,
              note: this.data.note
            });
            dataUpdated.weight = true;
          }

          // 检查是否有数据被更新
          success = Object.keys(dataUpdated).length > 0;
        } else {
          // 单项模式
          success = await api.health.addRecord(this.data.type, recordData);
        }
      }

      this.setData({ submitting: false });

      if (success) {
        wx.showToast({
          title: this.data.isEditMode ? '更新成功' : '添加成功',
          icon: 'success',
          duration: 1500
        });
        
        // 尝试触发数据更新事件
        try {
          console.log('准备通知前一页面数据已更新');
          const pages = getCurrentPages();
          // 向所有页面设置刷新标志
          pages.forEach(page => {
            if (page.route.includes('bloodsugardetail') || 
                page.route.includes('bloodpressuredetail') || 
                page.route.includes('weightdetail')) {
              if (typeof page.setData === 'function') {
                console.log(`设置页面 ${page.route} 的刷新标志`);
                page.setData({ 
                  needRefresh: true,
                  lastFetchTime: null
                });
                // 清除页面缓存
                if (typeof page.clearAllCache === 'function') {
                  page.clearAllCache();
                }
                // 触发立即刷新
                if (typeof page.fetchData === 'function') {
                  setTimeout(() => page.fetchData(), 100);
                }
              }
            }
          });
          
          // 通过事件通道通知上一个页面
          const eventChannel = this.getOpenerEventChannel();
          if (eventChannel && typeof eventChannel.emit === 'function') {
            console.log('通过事件通道通知前一页面数据已更新');
            eventChannel.emit('recordAdded', { 
              type: this.data.type,
              timestamp: new Date().getTime(),
              isEdit: this.data.isEditMode
            });
          }
        } catch (error) {
          console.error('通知数据更新失败:', error);
        }
        
        // 延迟返回，确保用户看到成功提示
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 500);
      } else {
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('提交记录失败:', error);
      this.setData({ submitting: false });
      wx.showToast({
        title: '提交失败: ' + (error.message || '请重试'),
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 输入值变化时触发验证
  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [field]: value
    }, () => {
      this.checkForm()
    })
  },
  
  // 日期选择器变化事件
  bindDateChange(e) {
    this.setData({
      recordDate: e.detail.value
    });
    this.checkForm();
  },
  
  // 时间选择器变化事件
  bindTimeChange(e) {
    this.setData({
      recordTime: e.detail.value
    });
    this.checkForm();
  },

  /**
   * 加载记录数据
   */
  async loadRecord(id, type) {
    try {
      console.log('开始加载记录:', { id, type });
      const record = await api.health.getRecord(type, id);
      
      if (!record) {
        console.warn('记录不存在:', { id, type });
        wx.showToast({
          title: '记录不存在',
          icon: 'none'
        });
        return;
      }
      
      console.log('加载到记录数据:', record);
      
      const recordDate = new Date(record.timestamp);
      const date = recordDate.toISOString().slice(0, 10);
      const hour = String(recordDate.getHours()).padStart(2, '0');
      const minute = String(recordDate.getMinutes()).padStart(2, '0');
      const time = `${hour}:${minute}`;
      
      // 设置记录数据
      const data = {
        recordDate: date,
        recordTime: time,
        note: record.note || ''
      };
      
      switch (type) {
        case 'glucose':
          data.glucose = String(record.value);
          break;
        case 'bloodPressure':
          data.systolic = String(record.systolic);
          data.diastolic = String(record.diastolic);
          break;
        case 'weight':
          data.weight = String(record.value);
          break;
      }
      
      console.log('设置表单数据:', data);
      this.setData(data);
      
      // 确保表单验证正确运行
      setTimeout(() => {
        this.checkForm();
      }, 100);
      
    } catch (err) {
      console.error('加载记录失败:', err);
      wx.showToast({
        title: '加载记录失败',
        icon: 'none'
      });
    }
  },

  // 格式化要提交的记录数据
  formatRecordData() {
    const { 
      type, glucose, systolic, diastolic, weight, 
      note, period, recordDate, recordTime 
    } = this.data;
    
    // 创建时间戳
    const timestamp = this.formatTimestamp();
    
    // 根据类型构建不同的数据对象
    let recordData = { timestamp, note };
    
    switch (type) {
      case 'bloodPressure':
        recordData = {
          ...recordData,
          systolic: parseInt(systolic),
          diastolic: parseInt(diastolic),
          period
        };
        break;
      case 'glucose':
        recordData = {
          ...recordData,
          value: parseFloat(glucose),
          period
        };
        break;
      case 'weight':
        recordData = {
          ...recordData,
          value: parseFloat(weight)
        };
        break;
    }
    
    return recordData;
  },
  
  // 格式化时间戳
  formatTimestamp() {
    const { recordDate, recordTime } = this.data;
    
    // 解析日期和时间
    const [year, month, day] = recordDate.split('-').map(Number);
    const [hours, minutes] = recordTime.split(':').map(Number);
    
    // 创建Date对象
    const recordDateTime = new Date(year, month - 1, day, hours, minutes);
    
    return recordDateTime.getTime();
  },
})